package cn.iocoder.aics.module.member.controller.app.chathistory;

import cn.iocoder.aics.framework.common.pojo.CommonResult;
import cn.iocoder.aics.framework.common.pojo.PageParam;
import cn.iocoder.aics.framework.common.pojo.PageResult;
import cn.iocoder.aics.framework.common.util.object.BeanUtils;
import cn.iocoder.aics.module.member.controller.admin.chatcontext.vo.ChatContextPageReqVO;
import cn.iocoder.aics.module.member.controller.admin.chatcontext.vo.ChatContextSaveReqVO;
import cn.iocoder.aics.module.member.controller.admin.chathistory.vo.ChatHistoryPageReqVO;
import cn.iocoder.aics.module.member.controller.admin.chathistory.vo.ChatHistoryRespVO;
import cn.iocoder.aics.module.member.controller.admin.chathistory.vo.ChatHistorySaveReqVO;
import cn.iocoder.aics.module.member.controller.app.chathistory.vo.*;
import cn.iocoder.aics.module.member.dal.dataobject.chatcontext.ChatContextDO;
import cn.iocoder.aics.module.member.dal.dataobject.chathistory.ChatHistoryDO;
import cn.iocoder.aics.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.aics.module.member.service.chatcontext.ChatContextService;
import cn.iocoder.aics.module.member.service.chathistory.ChatHistoryService;
import cn.iocoder.aics.module.member.service.chathistory.DsService;
import cn.iocoder.aics.module.member.service.user.MemberUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static cn.iocoder.aics.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.aics.framework.common.pojo.CommonResult.success;
import static cn.iocoder.aics.module.member.enums.ErrorCodeConstants.USER_NOT_EXISTS;
import static cn.iocoder.aics.module.member.enums.ErrorCodeConstants.USER_POINT_NOT_ENOUGH;

@Tag(name = "管理后台 - 聊天记录")
@RestController
@RequestMapping("/member/chat-history")
@Validated
public class AppChatHistoryController {

    @Resource
    private ChatHistoryService chatHistoryService;

    @Resource
    private ChatContextService chatContextService;

    @Resource
    private DsService dsService;
    @Resource
    private MemberUserService userService;
    @PostMapping("/create")
    @Operation(summary = "创建聊天记录")
    @PermitAll
    @Transactional
    public CommonResult<ChatResponseVo> createChatHistory(@Valid @RequestBody ChatRequestVo chatRequestVo) {

        try {
            MemberUserDO user = userService.getUser(chatRequestVo.getUserId());
            if (user == null) {
                throw exception(USER_NOT_EXISTS);
            }
            if (user.getShareCount()<=0){
                throw exception(USER_POINT_NOT_ENOUGH);
            }
            String question = chatRequestVo.getQuestion();
            if (chatRequestVo.getContextId() == 0L){
                ChatContextSaveReqVO createReqVO = new ChatContextSaveReqVO();
                createReqVO.setName(question);
                createReqVO.setUserId(chatRequestVo.getUserId());
                Long chatContextID = chatContextService.createChatContext(createReqVO);
                createReqVO.setId(chatContextID);
                chatRequestVo.setContextId(chatContextID);
            }

            ChatHistoryPageReqVO pageReqVO = new ChatHistoryPageReqVO();
            pageReqVO.setUserId(chatRequestVo.getUserId());
            pageReqVO.setContextId(chatRequestVo.getContextId());
            pageReqVO.setPageSize(ChatHistoryPageReqVO.PAGE_SIZE_NONE);
            PageResult<ChatHistoryDO> pageResult = chatHistoryService.getChatHistoryPage(pageReqVO);


            Message systemMessage = Message.builder()
                    .role("system")
                    .content("请直接给出简明答案，不需要分析过程。并且禁用推理步骤，返回结果不超过1500字")
                    .build();
            List<Message> messages = new ArrayList<>();
            messages.add(systemMessage);
            for (ChatHistoryDO chatHistoryDO : pageResult.getList()) {
                Message message = Message.builder()
                        .role("user")
                        .content(chatHistoryDO.getQuestion())
                        .build();
                messages.add(message);
                Message answer = Message.builder()
                        .role("assistant")
                        .content(chatHistoryDO.getAnswer())
                        .build();
                messages.add(answer);
            }
            Message userMessage = Message.builder()
                    .role("user")
                    .content(question)
                    .build();
            messages.add(userMessage);
            CompletionRequest completionRequest = CompletionRequest.builder()
                    .model("deepseek-chat")
                    .messages(messages)
                    .stream(false)
                    .maxTokens(2000)
                    .build();

            ChatHistorySaveReqVO createReqVO = new ChatHistorySaveReqVO();
            createReqVO.setQuestion(question);
            createReqVO.setUserId(chatRequestVo.getUserId());
            createReqVO.setContextId(chatRequestVo.getContextId());
            createReqVO.setType(1);

            String answer = dsService.postDataToApi(completionRequest);
            // 使用 Jackson 将 answer 字符串转换为 ChatResponse 对象
            ObjectMapper objectMapper = new ObjectMapper();
            ChatResponse chatResponse = objectMapper.readValue(answer, ChatResponse.class);
            // 提取 content 字段
            String content = chatResponse.getChoices().get(0).getMessage().getContent();
            createReqVO.setAnswer(content);
            Long id = chatHistoryService.createChatHistory(createReqVO);
            // 创建 ChatResponseVo 对象
            ChatResponseVo chatHistory = new ChatResponseVo();
            chatHistory.setId(id);
            chatHistory.setAnswer(content);
            chatHistory.setContextId(chatRequestVo.getContextId());
            return success(chatHistory);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @GetMapping("/get")
    @Operation(summary = "获得聊天记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult< List<ChatHistoryRespVO>> getChatHistory(@RequestParam("id") Long id) {
        ChatHistoryPageReqVO pageReqVO = new ChatHistoryPageReqVO();
        pageReqVO.setContextId(id);
        pageReqVO.setPageSize(ChatHistoryPageReqVO.PAGE_SIZE_NONE);
        PageResult<ChatHistoryDO> pageResult = chatHistoryService.getChatHistoryPage(pageReqVO);
        List<ChatHistoryRespVO> bean = BeanUtils.toBean(pageResult.getList(), ChatHistoryRespVO.class);
        // 倒序排列
        Collections.reverse(bean);
        return success(bean);
    }
    @GetMapping("/delete/{id}")
    @Operation(summary = "删除聊天记录")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteChatHistory(@PathVariable("id") Long id) {
        chatHistoryService.deleteChatHistory(id);
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "获得聊天记录分页")
    public CommonResult<ChatContextGroupedRespVO> getChatHistoryPage(@Valid ChatContextPageReqVO pageReqVO) {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<ChatContextDO> chatContextPage = chatContextService.getChatContextPage(pageReqVO);
        List<ChatContextDO> chatContextRespVOList = chatContextPage.getList();
        List<ChatContextDO> within3Days = new ArrayList<>();
        List<ChatContextDO> between3And7Days = new ArrayList<>();
        List<ChatContextDO> between7And30Days = new ArrayList<>();
        List<ChatContextDO>  over30Days= new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (ChatContextDO chatContextDO : chatContextRespVOList) {
            LocalDateTime createdAt = chatContextDO.getCreateTime();
            long daysBetween = ChronoUnit.DAYS.between(createdAt, now);
            if (daysBetween <= 3) {
                within3Days.add(chatContextDO);
            } else if (daysBetween >3 &&daysBetween <= 7) {
                between3And7Days.add(chatContextDO);
            } else if (daysBetween >7 &&daysBetween < 30) {
                between7And30Days.add(chatContextDO);
            }else {
                over30Days.add(chatContextDO);
            }
        }
        ChatContextGroupedRespVO groupedRespVO = new ChatContextGroupedRespVO();
        groupedRespVO.setWithin3Days(within3Days);
        groupedRespVO.setBetween3And7Days(between3And7Days);
        groupedRespVO.setBetween7And30Days(between7And30Days);
        groupedRespVO.setOver30Days(over30Days);

        return success(groupedRespVO);
    }

}